package post

import (
	"community-service/cmd/api/internal/models/model"
	"community-service/cmd/api/internal/svc"
	"community-service/cmd/api/internal/types"
	e "community-service/pkg/errorx"
	"context"
	"google.golang.org/grpc/codes"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserApprovePostLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserApprovePostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserApprovePostLogic {
	return &UserApprovePostLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserApprovePostLogic) UserApprovePost(req *types.UserPostApproveReq) (resp *types.Empty, err error) {
	// 参数验证

	// 检查帖子是否存在
	var post model.CsCommunityPost
	if err = l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityPost{}).
		Where("id = ?", req.Id).Find(&post).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	if post.ID == 0 {
		return nil, e.NewGrpcErr(codes.NotFound, e.PostNotFound)
	}

	// 检查是否已经点赞过
	var existingApprove model.CsCommunityPostApprove
	if err = l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityPostApprove{}).
		Where("post_id = ? AND create_user = ?", req.Id, req.UserId).
		Find(&existingApprove).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	if req.Action {
		// 点赞操作
		if existingApprove.ID > 0 {
			// 已经点赞过，不需要重复操作
			return &types.Empty{}, nil
		}

		// 创建点赞记录
		approve := &model.CsCommunityPostApprove{
			PostID:     req.Id,
			CreateUser: req.UserId,
		}

		if err = l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityPostApprove{}).Create(approve).Error; err != nil {
			return nil, e.NewGrpcErr(codes.Internal, e.DBError)
		}
	} else {
		// 取消点赞操作
		if existingApprove.ID == 0 {
			// 没有点赞记录，不需要操作
			return &types.Empty{}, nil
		}

		// 删除点赞记录
		if err = l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityPostApprove{}).
			Where("id = ?", existingApprove.ID).Delete(&model.CsCommunityPostApprove{}).Error; err != nil {
			return nil, e.NewGrpcErr(codes.Internal, e.DBError)
		}
	}

	return &types.Empty{}, nil
}
